package com.hk.Mgr.web.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpSession;

import com.hk.service.IUserChannel;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.SessionConstants;
import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.Token;
import com.hk.Mgr.web.message.sys.SysUserReq;
import com.hk.Mgr.web.message.sys.SysUserRes;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.ReqToModelHelper;
import com.hk.commons.SqlFilter;
import com.hk.commons.entity.Organization;
import com.hk.commons.entity.sys.SysResource;
import com.hk.commons.entity.sys.SysRole;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.entity.sys.SysUserRoles;
import com.hk.commons.utils.sys.MD5Crypter;
import com.hk.service.IOrganization;
import com.hk.service.sys.ISysModuleResource;
import com.hk.service.sys.ISysResource;
import com.hk.service.sys.ISysRole;
import com.hk.service.sys.ISysRoleModules;
import com.hk.service.sys.ISysUser;
import com.hk.service.sys.ISysUserRoles;

/**
 * @author lemon 用户实现类
 */
@Controller
@RequestMapping(value = BaseCtrl.CommonRootPath + "/LoginCtrl")
public class LoginCtrl extends BaseCtrl {

	@Autowired
	private ISysUser sysUserService;

	@Autowired
	private ISysUserRoles sysUserRolesService;

	@Autowired
	private ISysRole sysRoleService;

	@Autowired
	private IOrganization orgService;

	@Autowired
	private IUserChannel userChannelService;


	@Autowired
	private ISysRoleModules sysRoleModulesService;

	@Autowired
	private ISysModuleResource sysModuleResourceService;

	@Autowired
	private ISysResource sysResourceService;

	/**
	 * @Title: getSysUserById
	 * @Description: 根据id获取用户
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ResponseBase<SysUserRes> login(@RequestBody SysUserReq req) {
		ResponseBase<SysUserRes> resp = new ResponseBase<SysUserRes>();
		try {
			String cpwd = req.getPwd();

			logger.info("password = " + cpwd);
			if (StringUtils.isBlank(req.getName()) || StringUtils.isBlank(cpwd)) {
				resp.setMsg("参数错误，用户名或者密码为空");
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				logger.error("method[login]:account is empty or pwd is empty.");
				return resp;
			}

			logger.info("method[login]:account=" + req.getName());


			//离职和销户都不能登录
			SysUser user = sysUserService.getByPhoneNum(req.getName());
			if (user == null || (user.getIsInside() !=null && user.getIsInside() ==0) ) {
				resp.setMsg("用户不存在");
				logger.info("method[login] user is not exist : name =" + req.getName());
				resp.setResultCode(StatusCode.USERNAME_ERROR.key());
				return resp;
			}

			if(user.getOnType() != null && user.getOnType() == 1){
				resp.setMsg("用户离职，不能登录");
				logger.info("method[login] user is leave : name =" + req.getName());
				resp.setResultCode(StatusCode.USERNAME_ERROR.key());
				return resp;
			}

			if (!cpwd.equalsIgnoreCase(user.getPwd())) {
				resp.setMsg("密码错误");
				resp.setResultCode(StatusCode.PASSWORD_ERROR.key());
				return resp;
			}

			setUserToken(user);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("登录成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	public LoginCtrl() {
	}

	// 登录同时设置超时时间
	private void setUserToken(SysUser sysUser) {
		// 设置登录超时时间
		getSession().setMaxInactiveInterval(
				SessionConstants.LOGIN_SESSION_TIMEOUT); // 设置登录超时为8个小时
		// 存放在token里面
		Token t = new Token();
		t.setId(sysUser.getId());
		t.setName(sysUser.getName());
		t.setPwd(sysUser.getPwd());
		t.setAge(sysUser.getAge());
		t.setRealName(sysUser.getRealName());

		if (sysUser.getBirthday() != null) {
			t.setBirthday(new Timestamp(sysUser.getBirthday()));
		}

		// 添加部门信息
		if (sysUser.getOrgId() != null) {
			Organization org = orgService.findById(sysUser.getOrgId());
			t.setOrgId(sysUser.getOrgId());
			if (org != null) {
				t.setDepName(orgService.getDepNameById(org.getId()));
			}
		}

		if (sysUser.getEntryTime() != null) {
			t.setEntryTime(new Timestamp(sysUser.getEntryTime()));
		}

		if (sysUser.getEntryTime() != null) {
			t.setEntryTime(new Timestamp(sysUser.getEntryTime()));
		}

		t.setHealthStatus(sysUser.getHealthStatus());
		t.setIdentity(sysUser.getIdentity());

		if (sysUser.getLeaveTime() != null) {
			t.setLeaveTime(new Timestamp(sysUser.getLeaveTime()));
		}

		t.setOnJobTime(sysUser.getOnJobTime());
		t.setOnType(sysUser.getOnType());
		t.setAccountId(sysUser.getAccountId());
		List<String> sysUri = new ArrayList<String>();
		List<String> typeAndFlag = new ArrayList<String>();
		List<String> funcBtns = new ArrayList<String>(); // 功能按钮
		List<SysUserRoles> relSysUserRoles = sysUserRolesService
				.getByUserAccount(sysUser.getName());

		SqlFilter hqlFilter = new SqlFilter("SysResource");
		String hql = " LEFT JOIN SysModuleResource smr ON t.Id=smr.ResourceId"
				+ " WHERE smr.ModuleId IN (SELECT rm.ModuleId FROM SysRoleModules rm LEFT JOIN SysRole sr ON rm.roleid=sr.id"
				+ " WHERE sr.Id IN (SELECT ur.RoleId FROM SysUser su LEFT JOIN SysUserRoles ur ON su.Name=ur.Account "
				+ " WHERE su.Name='" + sysUser.getName() + "'))";
		hqlFilter.addSql(hql);
		logger.info("hql = {}", hql);
		List<SysResource> sysResourceList = sysResourceService
				.findBySqlFilter(hqlFilter);
		if (sysResourceList != null && sysResourceList.size() != 0) {
			// 查询带有操作标志记录
			hqlFilter = new SqlFilter("SysResource");
			hql = " WHERE t.ResFlag is not null";
			List<SysResource> srList = sysResourceService
					.findBySqlFilter(hqlFilter);

			for (SysResource sysResource : sysResourceList) {
				
				/*
				for (SysResource sr : srList) {
					String btnName = sr.getResFlag() + "_"
							+ sysResource.getResType();

					// 功能按钮以大于80开始标志
					if (80 < sysResource.getResType()
							&& sysResource.getParentId() == sr.getId()) {

						funcBtns.add(btnName);
					}
				}
				*/
				// 功能按钮以大于80开始标志
				if (80 < sysResource.getResType()) {
					String btnName = sysResourceService.findById(
							sysResource.getParentId()).getResFlag()
							+ "_" + sysResource.getResType();
					//logger.info("SysResource = {}", sysResource.toString());
					funcBtns.add(btnName);
				}

				
				String str = sysResource.getResType() + ";"
						+ sysResource.getResFlag();
				typeAndFlag.add(str);
				if (!StringUtils.isEmpty(sysResource.getUri())) {
					String[] uris = sysResource.getUri().split(",");
					for (String s : uris) {
						sysUri.add(s);
					}
				}
			}
		}

		logger.info("funcBtns size={}", funcBtns.size());
		t.setFuncBtns(funcBtns);

		logger.info("<---------------------funcBtns--------------------->");
		logger.info(" funcBtns = {}", Arrays.toString(funcBtns.toArray()));
		logger.info("<---------------------funcBtns--------------------->");


		t.setSysUri(sysUri);
		t.setTypeAndFlag(typeAndFlag);
		// 获取角色
		String roleNames = "";
		String roleIds = "";
		for (SysUserRoles sysUserRole : relSysUserRoles) {
			Long roleId = sysUserRole.getRoleId();
			SysRole sysRole = sysRoleService.findById(roleId);
			roleNames = roleNames + sysRole.getName() + ",";
			roleIds = roleIds + roleId + ",";
		}
		if (StringUtils.isNotBlank(roleNames)) {
			roleNames = roleNames.substring(0, roleNames.length() - 1);
		}
		if (StringUtils.isNotBlank(roleIds)) {
			roleIds = roleIds.substring(0, roleIds.length() - 1);
		}
		t.setRoleNames(roleNames);
		t.setRoleIds(roleIds);


		getSession().setAttribute(SessionConstants.Token, t);
	}

	/**
	 * 用户注销
	 * 
	 * @param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/loginOut")
	public ResponseBase<SysUserRes> loginOut() {
		ResponseBase<SysUserRes> resp = new ResponseBase<>();
		HttpSession session = getSession();
		session.removeAttribute(SessionConstants.Token);
		resp.setResultCode(StatusCode.SUCCESS.key());
		resp.setMsg("注销成功");
		return resp;
	}

	/**
	 * 修改用户密码
	 * 
	 * @param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateUserPwd")
	public ResponseBase<SysUserRes> updateUserPwd(@RequestBody SysUserReq req) {
		ResponseBase<SysUserRes> resp = new ResponseBase<SysUserRes>();
		try {
			if (req == null) {
				resp.setMsg("参数错误");
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				logger.error("method[updateUserPwd]:req is empty.");
			} else {
				logger.info("method[updateUserPwd]:req=" + this.getAccount());

				SysUser respSysUser = sysUserService.getByAccount(this
						.getAccount());

				if (respSysUser == null) {
					resp.setResultCode(StatusCode.DATA_EXISTS.key());
					resp.setMsg("此用户不存.");
					return resp;
				} else {
					String opwd = req.getOpwd();
					if (!opwd.equals(respSysUser.getPwd())) {
						resp.setResultCode(StatusCode.ERROR.key());
						resp.setMsg("修改失败，原密码不对");
						return resp;
					} else {
						respSysUser.setPwd(MD5Crypter.md5Encrypt(req.getPwd()));
						sysUserService.update(respSysUser);
						resp.setResultCode(StatusCode.SUCCESS.key());
						resp.setMsg("修改成功");
						return resp;
					}
				}
			}

		} catch (Exception ex) {
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
			logger.error(ex.getMessage(), ex);
		}
		return resp;
	}

	/**
	 * @Title: getSysUserById
	 * @Description: 获取当前用户信息
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/getCurrentUserInfo", method = RequestMethod.POST)
	public ResponseBase<SysUserRes> getCurrentUserInfo(
			@RequestBody SysUserReq req) {
		ResponseBase<SysUserRes> resp = new ResponseBase<SysUserRes>();
		try {
			SysUser sysUser = sysUserService.getByAccount(this.getAccount());
			SysUserRes sresp = new SysUserRes();
			ReqToModelHelper.copyReqValueToModel(sysUser, sresp);
			sresp.setBirthday(sysUser.getBirthday());
			sresp.setEntryTime(sysUser.getEntryTime());
			sresp.setLeaveTime(sysUser.getLeaveTime());
			sresp.setRegistCts(sysUser.getRegistCts());
			List<SysUserRoles> sysUserRolesList = sysUserRolesService
					.getByUserAccount(sysUser.getName());
			String sysRoleNames = "";
			for (SysUserRoles sysUserRoles : sysUserRolesList) {
				SysRole sysRole = sysRoleService.findById(sysUserRoles
						.getRoleId());
				if (sysRole != null) {
					sysRoleNames += "," + sysRole.getName();
				}
			}

			sresp.setSysUserRoleList(sysUserRolesList);
			sresp.setSysRoleNames(StringUtils.isEmpty(sysRoleNames) ? ""
					: sysRoleNames.substring(1));

			// 添加部门信息
			if (sysUser.getOrgId() != null) {
				Organization org = orgService.findById(sysUser.getOrgId());
				sresp.setOrgId(sysUser.getOrgId());
				if (org != null) {
					sresp.setDutyName(org.getName());
					sresp.setDutyFullName(org.getFlag02());
					sresp.setChannelName(userChannelService.getChannelNameByChannelId(org.getChannel()));
					sresp.setOrgDepName(orgService.getDepNameById(org.getId()));
				}
			}

			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setResult(sresp);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}
}
